<template>
	<view>
		<!-- 自定义导航栏 -->
		<view class="navbar" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
			<view class="back-btn" @tap="goBack">
				<uni-icons type="left" size="24" color="#333"></uni-icons>
			</view>
			<view class="title">查看订单</view>
		</view>

		<!-- 状态选项卡 -->
		<view class="tabs">
			<view v-for="(item, index) in tabList" :key="index"
				:class="['tab-item', currentTab === index ? 'active' : '']" @tap="switchTab(index)">
				{{item}}
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" :style="{ height: scrollViewHeight }" scroll-y @scrolltolower="loadMore"
			v-if="orderList.length > 0">
			<view class="order-item" v-for="(item, index) in filteredOrders" :key="index">
				<view class="order-header">
					<text class="order-sn">订单号：{{item.orderSn}}</text>
					<text class="order-status" :style="{color: statusColors[item.orderStatus]}">
						{{statusMap[item.orderStatus]}}
					</text>
				</view>
				<view class="goods-info">
					<image class="goods-img" :src="item.goodsInfo.goodsImage1" mode="aspectFill" />
					<view class="goods-detail">
						<view class="price">¥{{item.paymentAmount}}</view>
						<view class="name">{{item.goodsInfo.goodsName || '商品已下架'}}</view>
						<view class="quantity">数量：{{item.quantity}}</view>
					</view>
				</view>
				<view class="order-footer" v-if="item.orderStatus === 0">
					<button class="action-btn">立即支付</button>
				</view>
			</view>
			<view class="load-more">
				{{loading ? '加载中...' : '没有更多了'}}
			</view>
		</scroll-view>

		<!-- 空状态 -->
		<view class="empty" v-else>
			<!-- 			<image src="/static/empty-order.png" class="empty-img" /> -->
			<view class="empty-text">暂无相关订单</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 0,
				tabList: ['全部', '待支付', '已支付', '已发货', '已完成', '退换货'],
				statusMap: ['待支付', '已支付', '已发货', '已完成', '退换货中'],
				statusColors: ['#f40', '#07c160', '#1989fa', '#909399', '#ff976a'],
				orderList: [],
				userId: null,
				loading: false,
				pageParams: {
					page: 1,
					pageSize: 10,
					total: 0
				},
				safeAreaInsets: {
					top: 0,
					bottom: 0
				}
			}
		},
		computed: {
			// 根据选项卡过滤订单
			filteredOrders() {
				if (this.currentTab === 0) return this.orderList
				return this.orderList.filter(item => item.orderStatus === this.currentTab - 1)
			},
			// 动态计算滚动区域高度
			scrollViewHeight() {
				return `calc(100vh - ${this.safeAreaInsets.top + 100}px)` // 调整高度以适配导航栏和状态栏
			}
		},
		async onLoad() {
			await this.getUserInfo()
			this.getOrderList()
			this.getSafeAreaInsets()
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 切换选项卡
			switchTab(index) {
				this.currentTab = index
			},

			// 获取用户信息
			async getUserInfo() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/system/user/profile',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					})
					this.userId = res.data.data.userId
				} catch (e) {
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					})
				}
			},

			// 获取订单列表
			async getOrderList() {
				if (!this.userId) return

				this.loading = true
				try {
					const {
						data
					} = await uni.request({
						url: `http://localhost:8080/orderInfo/orderInfo/list`,
						data: {
							userId: this.userId,
							page: this.pageParams.page,
							pageSize: this.pageParams.pageSize
						},
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					})

					if (data.code === 200) {
						// 获取商品详细信息
						const orders = await Promise.all(
							data.rows.map(async order => {
								const goodsRes = await uni.request({
									url: `http://localhost:8080/goods/goods/${order.goodsId}`,
									header: {
										'Authorization': uni.getStorageSync('token')
									}
								})
								return {
									...order,
									goodsInfo: {
										...goodsRes.data.data,
										goodsImage1: 'http://localhost:8080' + goodsRes.data.data
											.goodsImage1
									}
								}
							})
						)

						this.orderList = [...this.orderList, ...orders]
						this.pageParams.total = data.total
					}
				} finally {
					this.loading = false
				}
			},

			// 加载更多
			loadMore() {
				if (this.orderList.length < this.pageParams.total) {
					this.pageParams.page++
					this.getOrderList()
				}
			},

			// 获取安全区域信息
			getSafeAreaInsets() {
				uni.getSystemInfo({
					success: (res) => {
						this.safeAreaInsets = {
							top: res.safeArea ? res.safeArea.top : res.statusBarHeight,
							bottom: res.safeArea ? res.safeArea.bottom : 0
						};
					},
					fail: (err) => {
						console.error('获取系统信息失败:', err);
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 导航栏样式 */
	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between; // 确保内容在水平方向上分布
		padding: 0 20rpx;
		height: 90rpx; // 设置固定高度
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 10;

		.back-btn {
			display: flex;
			align-items: center; // 确保图标垂直居中
		}

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			text-align: center; // 确保标题在水平方向上居中
			flex: 1;
		}
	}

	/* 状态选项卡样式 */
	.tabs {
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		.tab-item {
			padding: 10rpx 20rpx;
			font-size: 30rpx;
			color: #666;
			position: relative;
		}

		.tab-item.active {
			color: #333;
			font-weight: bold;
			border-bottom: 4rpx solid #f40;
		}
	}

	/* 订单列表样式 */
	.order-list {
		height: calc(100vh - 100px);
	}

	.order-item {
		background-color: #fff;
		margin: 20rpx 30rpx;
		padding: 20rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.order-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			.order-sn {
				font-size: 26rpx;
				color: #666;
			}

			.order-status {
				font-size: 28rpx;
				font-weight: bold;
			}
		}

		.goods-info {
			display: flex;
			margin-bottom: 20rpx;

			.goods-img {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}

			.goods-detail {
				flex: 1;

				.price {
					font-size: 32rpx;
					color: #f40;
					margin-bottom: 10rpx;
				}

				.name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 10rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}

				.quantity {
					font-size: 24rpx;
					color: #999;
				}
			}
		}

		.order-footer {
			display: flex;
			justify-content: flex-end;

			.action-btn {
				padding: 10rpx 30rpx;
				background-color: #f40;
				color: #fff;
				border-radius: 50rpx;
				font-size: 28rpx;
				border: none;
			}
		}
	}

	.load-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	/* 空状态样式 */
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		background-color: #f7f8fa;

		.empty-img {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 20rpx;
		}

		.empty-text {
			font-size: 32rpx;
			color: #999;
		}
	}
</style>
